#include<iostream>
#include<functional> 
#include<string>
#include<websocketpp/config/asio_no_tls.hpp> 
#include<websocketpp/server.hpp> 


void print(const std::string& str)
{
  std::cout << str << std::endl;
}


typedef websocketpp::server<websocketpp::config::asio> wsserver_t;  

void HttpCallBack(websocketpp::server<websocketpp::config::asio>* wser ,websocketpp::connection_hdl hdl )
{
    wsserver_t::connection_ptr con = wser->get_con_from_hdl(hdl) ; //获取连接  
    std::cout << "body : " << con->get_request_body() << std::endl;  //打印请求正文  
    websocketpp::http::parser::request req = con->get_request(); //获取请求对象 
    std::cout << "method : " << req.get_method() << std::endl;  
    std::cout << "uri : " << req.get_uri() << std::endl ;  

    std::string body = "<html><body><h1>Hello World  </h1> </body></html>"; 
    con->set_body(body) ; //设置响应正文 
    con->append_header("Content-Type","text/html");  // 设置响应报头
    con->set_status(websocketpp::http::status_code::ok); //设置状态码
    
    wsserver_t::timer_ptr tp = wser->set_timer(5000,std::bind(print,"1111111111")); 
    tp->cancel();
}

void OpenCallBack(websocketpp::server<websocketpp::config::asio>* wser ,websocketpp::connection_hdl hdl )
{
    std::cout << "握手成功" << std::endl;
}

void CloseCallBack(websocketpp::server<websocketpp::config::asio>* wser ,websocketpp::connection_hdl hdl )
{

    std::cout << "连接断开" << std::endl;
}

void MessageCallBack(websocketpp::server<websocketpp::config::asio>* wser ,websocketpp::connection_hdl hdl, wsserver_t::message_ptr msg )
{
    //获取连接对象
    wsserver_t::connection_ptr con = wser->get_con_from_hdl(hdl);
    std::cout << "wsmsg :" << msg->get_payload() << std::endl ; 
    std::string rsp = "client say : " + msg->get_payload(); //响应信息 
    //发送响应信息 
    con->send(rsp,websocketpp::frame::opcode::text); //发送的类型，text/文本
}
int main()
{

  //1.创建webserver服务器
  websocketpp::server<websocketpp::config::asio> wser ; 

  //2设置日志等级
  wser.set_access_channels(websocketpp::log::alevel::none) ; //none 代表什么都没有 

  //3. 初始化 asio 调度器
  wser.init_asio(); 

  //4. 处理回调函数 
  wser.set_http_handler(bind(HttpCallBack,&wser,std::placeholders::_1)); //http请求处理 
  wser.set_open_handler(bind(OpenCallBack,&wser,std::placeholders::_1)); //打开连接 
  wser.set_close_handler(bind(CloseCallBack,&wser,std::placeholders::_1)); //关闭连接 
  wser.set_message_handler(bind(MessageCallBack,&wser,std::placeholders::_1,std::placeholders::_2)); //消息处理

  //5.设置监听
  wser.listen(8081);
  //开始获取连接 = accept 
  wser.start_accept(); 

  //运行服务器 
  wser.run();

  return 0;
}
